<template>
    <div class="mainContent">
        <div class="search">
            <div class="left">
                <div class="list" style="margin: 0">
                    <ul class="ulbox1">
                        <li :class="dataFlag?'active':''" class="libox1" @click="getType(dataFlag)">按月</li>
                        <li :class="!dataFlag?'active':''" class="libox1" @click="getType(!dataFlag)">按年</li>
                    </ul>
                    <Input search enter-button placeholder="请输入设备类型，编号" class="radiusBorder" style="width:230px" @on-search="onSearch" @on-enter="onSearch" v-model="keyword" clearable />
                    <Date-picker v-if="dataFlag" type="daterange"  placement="bottom-end" v-model="value" :clearable="false" :options = "options"  placeholder="选择日期" style="width: 220px;margin-left: 20px" @on-change="changeDate"></Date-picker>
                    <Date-picker v-if="!dataFlag" type="year" placeholder="选择年" v-model="data" :clearable="false" style="width: 220px;margin-left: 20px" :options = "optionsYear" @on-change="getDate"></Date-picker>
                    <input type="password" autocomplete="new-password" style="display: none" />
                </div>
            </div>
            <div class="right" style="margin: 0">
                <el-dropdown split-button size="small" @click="handleClick" v-if="btnList.includes('mach/maintain/report/exp')">
                    数据导出
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="goEXP">导出记录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </div>
        <div class="center">
            <div class="center_item">
                <div class="left">
                    <div class="title">
                        维修保养费用总计:
                        <span>{{payTotal}}</span>
                        元
                    </div>
                    <div class="chart" v-if="pieList.length >0">
                        <div id="piePay" :style="{ height: '100%',width :'100%'}"></div>
                    </div>
                    <div class="chart" v-if="pieList.length == 0">
                        <img src="./../../assets/images/common/rotary_nodata.png" alt="" style="display: block;width: 100%; height: 100%;">
                    </div>
                </div>
                <div class="right">
                    <div id="pieLine" :style="{ height: '100%',width :'100%'}"></div>
                </div>
            </div>
        </div>
        <div class="tabBox">
            <div class="tableList">
                <el-table :data="machList" border :stripe='true'>
                    <el-table-column  prop="machCode" label="设备编号" width="150"></el-table-column>
                    <el-table-column  prop="machTypeName" label="设备类型" width="180"></el-table-column>
                    <el-table-column  prop="payTotal" label="费用总计" width="180"></el-table-column>
                    <el-table-column label="维修保养费用统计" align="center">
                        <el-table-column v-for="(item,index) in DateList" :key="index" :label="dataFlag?item.substring(5,10):item" width="100">
                            <template slot-scope="porps">
                                <p>{{porps.row.dayPayList[index].payTotal}}</p>
                            </template>
                        </el-table-column>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <Modal v-model="exportModal" title="导出" width="500px;" :mask-closable="false" class-name='addModal'
               :footer-hide="true">
            <div style="margin:20px auto;text-align: center;"><img src="../../assets/images/common/succes-iocn.png" style="width: 60px;height: 60px;display: block;margin: auto" alt=""></div>
            <div style="margin:20px auto;text-align: center;">导出任务已创建！</div>
            <div style="margin:20px auto;text-align: center;display: flex;justify-content: center;align-items: center;">
                <p>系统正在处理，请稍后到</p>
                <router-link to="/exp/list">导出记录</router-link>
                <p>下载。</p>
            </div>
        </Modal>
    </div>
</template>

<script>
import {format,initFirstData,initLastData,getNowM,getAllDates} from "@/sever/utils.js";
import  {getMachmaintainReportByMonth,getMachmaintainReportByYear,getMachmaintainPayState,getMachmaintainReportEXP} from '@/api/keep'
export default {
    data() {
        return {
            options: {
                disabledDate(date) {
                    return date > Date.now();
                }
            },
            optionsYear:{
                disabledDate(date) {
                    return date > Date.now();
                }
            },
            colors: [
                "#FA5C90 ",
                "#46D9FF ",
                "#4990FE ",
                "#856DFE ",
                "#FFC880 ",
                "#29b6f6 ",
                "#8bc34a",
                "#fbc02d",
                "#b3e5fc",
                "#ef5350",
                "#4dd0e1",
                "#304ffe",
                "#ff4081",
                "#82b1ff",
                "#6a1b9a",
                "#f57f17",
                "#b71c1c",
                "#a5d6a7",
                "#ffab91",
                "#880e4f",
                "#f8bbd0"
            ],
            keyword: "",
            dataFlag:true,
            data:new Date(),
            deptId:"",
            dataPayList:[],
            machList:[],
            payList:[],
            payTotal:'',
            pieList:[],
            DateList:[],
            newDateList:[],
            newDate:"",
            lineList:[],
            lineDateList:[],
            exportModal: false,
            btnList:[],
            value:[],
            startDate:"",
            endDate:"",
            newStartDate:"",
            newEndDate:"",
        }
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        }
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.deptId = val.deptId;
                this.keyword ="";
                this.dataFlag = true;
                this.startDate = initFirstData();
                this.endDate =initLastData();
                this.value =[this.startDate,this.endDate];
                this.data =new Date();
                let data;
                data = format(this.data, "YYYY");
                this.newDate = JSON.parse(JSON.stringify(data));
                this.getStateList();
            }
        }
    },
    methods: {
        changeDate(value){
            this.value = value;
            this.startDate = this.value[0];
            this.endDate = this.value[1];
            let time = new Date(this.endDate).getTime() - new Date(this.startDate).getTime()
            if(time > 86400000 *31 || time < 86400000 ){
                this.$Modal.warning({
                    title: "提示",
                    content: "请选择1-31天内时间范围"
                });
                return;
            }
            this.getStateList();
        },
        tranFromDayPayList(arr){
            this.initData();
            for(let i = 0 ; i<this.newDateList.length; i++) {
                for(let j = 0; j < arr.length; j++){
                    if(this.newDateList[i].date == arr[j].date || this.newDateList[i].date == arr[j].month){
                        this.newDateList[i].payTotal += arr[j].payTotal
                    }
                }
            }
            return this.newDateList;
        },
        //统计图
        darwPie(){
            let onSpot = this.$echarts.init(document.getElementById("piePay"));
            let _that =  this;
            onSpot.setOption({
                tooltip: {
                    trigger: "item",
                    formatter: "{a} <br/>{b}: {c} ({d}%)"
                },

                legend: {
                    orient: 'vertical',  //垂直显示
                    y: 'center',    //延Y轴居中
                    x: 'left', //居右显示
                    padding:-0.5, //调节legend的位置
                    icon: 'circle',
                    textStyle: { //图例文字的样式
                        fontSize: 12
                    },
                    formatter:  function(name){
                        var total = 0;
                        var target;
                        for (var i = 0, l = _that.pieList.length; i < l; i++) {
                            total += _that.pieList[i].value;
                            if (_that.pieList[i].name == name) {
                                target = _that.pieList[i].value;
                            }
                        }
                        return name +' ' + target + '元';
                    }
                },
                series: [
                    {
                        name: '保养费用',
                        type: 'pie',
                        radius: '50%',
                        data: _that.pieList,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            });
        },
        darwLine(){
            let onSpot = this.$echarts.init(document.getElementById("pieLine"));
            let _that =  this;
            onSpot.setOption({
                tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                        var relVal = params[0].name;
                        for (var i = 0, l = params.length; i < l; i++) {
                            relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + params[i].value + '元'
                        }
                        return relVal;
                    }
                },
                color:this.colors,
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    axisTick: {
                        show: false
                    },
                    axisLine: {
                        lineStyle: {
                            color: "#BFBFBF",
                            type: 'dashed',
                        }
                    },
                    splitLine: {
                        //去除网格线
                        show: false,
                        lineStyle: {
                            type: 'dashed',
                            color:'#BFBFBF'
                        }
                    },
                    boundaryGap: false,
                    data: _that.lineDateList
                },
                yAxis: {
                    type: 'value'
                },
                series:_that.lineList
            })
        },
        getType(flag){
            if(flag){
                return
            }
            this.dataFlag  = !this.dataFlag;
            this.keyword = "";
            this.startDate = initFirstData();
            this.endDate =initLastData();
            this.value =[this.startDate,this.endDate];
            this.data =new Date();
            let data;
            data = format(this.data, "YYYY");
            this.newDate = JSON.parse(JSON.stringify(data));
            this.getStateList();
        },
        getStateList(){
            this.pieList =[];
            let params = this.dataFlag?
                {
                    deptId:this.deptId,
                    keyword:this.keyword,
                    endDate:this.endDate,
                    startDate:this.startDate,
                } :
                {
                    deptId:this.deptId,
                    keyword:this.keyword,
                    year:this.newDate,
                };
            getMachmaintainPayState(params).then(res=>{
                if(res.code == 200) {
                    this.payTotal =res.data.payTotal;
                    this.payList = res.data.payList;
                    this.payList.forEach((i,index)=>{
                        let obj = {
                            name:i.payName,
                            value:i.payValue,
                            itemStyle: {
                                normal: {
                                    color: this.colors[index],
                                }
                            }
                        }
                        this.pieList.push(obj);
                    })
                    if(this.dataFlag) {
                        this.getMonthList();
                    } else {
                        this.getYearList();
                    }
                    if(this.pieList.length > 0){
                        this.$nextTick(()=>{
                            this.darwPie();
                        })
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error=>{
                console.log(error)
            })
        },
        getMonthList(){
            this.$echarts.init(document.getElementById("pieLine")).clear();
            this.lineList =[];
            this.lineDateList =[];
            let params = {
                deptId:this.deptId,
                keyword:this.keyword,
                endDate:this.endDate,
                startDate:this.startDate,
            }
            getMachmaintainReportByMonth(params).then(res=>{
               if(res.code == 200) {
                   let list = res.data.dayPayList;
                   this.dataPayList =this.tranFromDayPayList(res.data.dayPayList);
                   let arr =[];
                   this.dataPayList.forEach(i=>{
                       arr.push((i.payTotal))
                       // this.lineList.push(i.payTotal);
                       this.lineDateList.push((i.date).substring(5,10))
                   })
                   this.lineList.push({
                       name: '费用总计',
                       type: 'bar',
                       barWidth: 15,
                       smooth: true , //true 为平滑曲线，false为直线
                       data: arr,
                   })
                   let objList = [];
                   for(let i = 0; i <this.payList.length; i ++){
                       let obj = {
                           name:this.payList[i].payName,
                           type:'line',
                           smooth:true,
                           payList:[],
                           data:[],
                       }
                       objList.push(obj);
                   }
                   for(let i = 0 ;i<list.length; i++) {
                       for(let j = 0; j<list[i].payList.length;j++){
                           for(let s = 0; s <objList.length; s++ ) {
                               if(objList[s].name == list[i].payList[j].payName) {
                                   objList[s].payList.push({
                                       date : list[i].payList[j].date,
                                       payTotal:list[i].payList[j].payValue,
                                   })
                               }
                           }
                       }
                   }
                   for(let i = 0 ;i<objList.length; i++){
                       objList[i].payList =this.tranFromDayPayList(objList[i].payList)
                   }
                   for(let i =0 ; i<objList.length;i++){
                       for(let j = 0; j <objList[i].payList.length;j++){
                           objList[i].data.push(objList[i].payList[j].payTotal);
                       }
                   }
                   this.lineList = [...this.lineList, ...objList];
                   this.machList = res.data.machList;
                   for(let i =0; i<this.machList.length; i++) {
                       this.machList[i].dayPayList = this.tranFromDayPayList(this.machList[i].dayPayList);
                   }
                   this.darwLine();
               } else {
                   this.$Message.warning(res.msg);
               }
            }).catch(error=>{
                console.log(error)
            })
        },
        getYearList(){
            this.$echarts.init(document.getElementById("pieLine")).clear();
            this.lineList =[];
            this.lineDateList =[];
            let params = {
                deptId:this.deptId,
                keyword:this.keyword,
                year:this.newDate,
            }
            getMachmaintainReportByYear(params).then(res=>{
                if(res.code == 200) {
                    this.machList = res.data.machList;
                    let list = res.data.monthPayList;
                    this.dataPayList =this.tranFromDayPayList(res.data.monthPayList);
                    let arr =[];
                    this.dataPayList.forEach(i=>{
                        arr.push((i.payTotal))
                        // this.lineList.push(i.payTotal);
                        this.lineDateList.push((i.date).substring(5,7))
                    })
                    this.lineList.push({
                        name: '费用总计',
                        type: 'bar',
                        barWidth: 15,
                        smooth: true , //true 为平滑曲线，false为直线
                        data: arr,
                    })
                    let objList = [];
                    for(let i = 0; i <this.payList.length; i ++){
                        let obj = {
                            name:this.payList[i].payName,
                            type:'line',
                            smooth:true,
                            payList:[],
                            data:[],
                        }
                        objList.push(obj);
                    }
                    for(let i = 0 ;i<list.length; i++) {
                        for(let j = 0; j<list[i].payList.length;j++){
                            for(let s = 0; s <objList.length; s++ ) {
                                if(objList[s].name == list[i].payList[j].payName) {
                                    objList[s].payList.push({
                                        date : (list[i].payList[j].date).substring(0,7),
                                        payTotal:list[i].payList[j].payValue,
                                    })
                                }
                            }
                        }
                    }

                    for(let i = 0 ;i<objList.length; i++){
                        objList[i].payList =this.tranFromDayPayList(objList[i].payList)
                    }
                    for(let i =0 ; i<objList.length;i++){
                        for(let j = 0; j <objList[i].payList.length;j++){
                            objList[i].data.push(objList[i].payList[j].payTotal);
                        }
                    }
                    this.lineList = [...this.lineList, ...objList];
                    this.darwLine();
                    for(let i =0; i<this.machList.length; i++) {
                        this.machList[i].dayPayList = this.tranFromDayPayList(this.machList[i].monthPayList);
                    }
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error=>{
                console.log(error)
            })
        },
        onSearch() {
            this.initData();
            this.getStateList();
        },
        getDate(value) {
            this.initData();
            let data = value;
            this.newDate = JSON.parse(JSON.stringify(data));
            this.getStateList();
        },
        handleClick() {
            var formdata = new FormData();
            formdata.append("deptId", this.deptId);
            formdata.append("keyword", this.keyword);
            if(this.dataFlag){
                formdata.append("startDate", this.startDate);
                formdata.append("endDate", this.endDate);
            } else {
                formdata.append("year", this.newDate);
            }
            let config = {
                headers: { "Content-Type": "multipart/form-data" }
                // headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }
            };
            getMachmaintainReportEXP(formdata,config).then(res=>{
                if(res.code == 200) {
                    this.exportModal = true;
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error=>{
                console.log(error)
            })   
        },
        goEXP() {
            this.$router.push({path: "/exp/list"});
        },
        initData(){
            this.newDateList =[];
            this.DateList = [];
            if(this.dataFlag){
                this.DateList = getAllDates(this.startDate,this.endDate);
                this.DateList.forEach(i=>{
                    let obj = {
                        date : i,
                        payTotal:0,
                    }
                    this.newDateList.push(obj)
                })
            } else {
                // this.DateList.length = 12;
                for (let i = 1; i < 13; i++){
                    let str = i > 9 ?i: '0' + i;
                    let obj = {
                        date:this.newDate+'-'+ str,
                        payTotal:0,
                    }
                    this.DateList.push(this.newDate+'-'+ str)
                    this.newDateList.push(obj)
                }
            }
        }
    },
    mounted() {
        this.startDate = initFirstData();
        this.endDate =initLastData();
        this.value =[this.startDate,this.endDate];
        let data = format(new Date(), "YYYY-MM");
        this.newDate = JSON.parse(JSON.stringify(data));
        this.deptId = this.$store.state.porjectObject.deptId;
        this.btnList = JSON.parse(localStorage.getItem("arr"));
        this.initData();
        this.getStateList();
    }
}
</script>

<style scoped lang="less">
@import "./../../assets/style/themeBase.less";
</style>

<style scoped lang="scss">
// @import "./../../assets/style/mach/mainContent.scss";
@import "./../../assets/style/mach/msgModal.scss";
.mainContent{
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    background: #F5F5F5;
    .search {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-radius: 10px;
            background:#fff;
            padding: 20px;
            box-sizing: border-box;
            &.searchBox{
                justify-content: flex-start;
                flex-wrap: wrap;
                // padding: 0 20px pxToRem(15);
                .list{
                    margin-right: 50px;
                    span{
                        &:first-of-type{
                            color: #373D41;
                            font-family: MicrosoftYaHeiLight;
                        }
                    }

                }
            }
            .left{
                width: 50%;
                /deep/ .ivu-tabs-bar{
                    width: 100%;
                    margin: 0 auto;
                    border: none;
                }
                /deep/ .ivu-tabs-tab{
                    padding-bottom: 20px;
                    box-sizing: border-box;
                }
            }
            .right{
                margin-top: -20px;
            }
            .list{
                display: flex;
                justify-content: flex-start;
                align-items: center;
                margin-right: 20px;
                margin-top: 20px;
                span{
                    width: 100px;
                    text-align: right;
                }
                .ulbox1{
                    list-style: none;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    margin-right: 20px;
                    .libox1{
                        width: 50px;
                        height: 32px;
                        text-align: center;
                        line-height: 32px;
                        color: var(--themeColor);
                        cursor: pointer;
                        border: 1px solid var(--themeColor);
                    }
                    li:first-child{
                        border-radius: 16px 0  0 16px;
                    }
                    li:last-child{
                        border-radius: 0 16px  16px 0;
                    }
                    .active{
                        background: var(--themeColor);
                        color: #fff;
                        border: none;
                    }
                }
            }
        }
        .tabBox{
            width:100%;
            margin-top: 10px;
            padding: 20px;
            box-sizing: border-box;
            background-color: #fff;
            border-radius: 10px;
            .tableList{
                width: 100%;
                /deep/ .el-table{
                    color: #181818;
                    font-family: MicrosoftYaHei;
                    font-size: 14px;
                    td,
                    th.is-leaf{
                        border-bottom: none;
                    }
                    tr{
                        border: none;
                    }
                    thead th{
                        color: #666666;
                        font-weight: 400;
                    }
                }
                /deep/ .el-table__row{
                    background-color: #fff;
                    cursor: pointer;
                }
                /deep/ .el-table--striped .el-table__body tr.el-table__row--striped td{
                    background-color: #F3F6FD ;
                    cursor: pointer;
                }
            }
        }
        .center{
            width: 100%;
            margin-top: 10px;
            border-radius: 10px;
            background: #fff;
            height: 4rem;
            display: flex;
            justify-content: center;
            align-items: center;
            .center_item{
                width: 96%;
                height: calc(100% - 0.4rem);
                display: flex;
                justify-content: space-between;
                align-items: center;
                .left{
                    width: 6rem;
                    height: 100%;
                    .title{
                        width: auto;
                        padding: 0.1rem;
                        height: 40px;
                        span{
                            color: var(--themeColor);
                        }
                    }
                    .chart{
                        width: 100%;
                        height: 330px;
                    }
                }
                .right{
                    width: calc(100% - 5rem);
                    height: 100%;
                }
            }
        }
}
>>>.el-button:focus, >>>.el-button:hover {
    color: var(--themeColor);
    border-color: var(--themeColor1);
    background-color: var(--themeColor2);
}
</style>
